<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="设备名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入设备名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备编号" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入设备编号"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备分组" prop="deviceGroupId">
        <el-select
          v-model="queryParams.deviceGroupId"
          placeholder="请选择设备分组"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="item in groupOptions"
            :key="item.groupId"
            :label="item.name"
            :value="item.groupId"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="设备分类" prop="deviceClassId">
        <el-select
          v-model="queryParams.deviceClassId"
          placeholder="请选择设备分类"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="item in classOptions"
            :key="item.classId"
            :label="item.name"
            :value="item.classId"
          />
        </el-select>
      </el-form-item> -->

      <el-form-item>
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['asset:device:set']"
          >新增</el-button
        >
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="deviceList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" width="60" align="center" type="index" />
      <el-table-column label="设备名称" align="center" prop="name"  :show-overflow-tooltip="true" />
      <el-table-column label="设备编号" align="center" prop="number" :show-overflow-tooltip="true" />
      <el-table-column label="设备分组" align="center" prop="deviceGroupName" :show-overflow-tooltip="true"  />
      <el-table-column label="设备分类" align="center" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ formateClass(scope.row.deviceClassId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="协议类型" align="center" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ formateProtocol(scope.row.deviceProtocolId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="建筑物" align="center" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ formateBuilding(scope.row.deviceBuildingId) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="协议类型" align="center" prop="protocolName" /> -->
      <!-- <el-table-column label="建筑物" align="center" prop="deviceBuildingId" /> -->
      <el-table-column label="控制模式" align="center" prop="controlType" :show-overflow-tooltip="true">
        <template #default="scope">
          <el-tag :type="scope.row.controlType === 0 ? 'info' : 'success'">
            {{ scope.row.controlType === 0 ? "手动" : "自动" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <!-- 创建人 -->
      <el-table-column label="创建人" align="center" prop="createUserName"  :show-overflow-tooltip="true" />
      <el-table-column
        label="操作"
        width="200"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <!-- <el-button
            link
            type="primary"
            icon="View"
            @click="handleDetail(scope.row)"
            v-hasPermi="['asset:device:set']"
            >详情</el-button
          > -->
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['asset:device:set']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['asset:device:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="deviceRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备编号" prop="number">
          <el-input v-model="form.number" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="设备分组" prop="deviceGroupId">
          <el-select
            v-model="form.deviceGroupId"
            placeholder="请选择设备分组"
            style="width: 100%"
          >
            <el-option
              v-for="item in groupOptions"
              :key="item.groupId"
              :label="item.name"
              :value="item.groupId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备分类" prop="deviceClassId">
          <el-select
            v-model="form.deviceClassId"
            placeholder="请选择设备分类"
            style="width: 100%"
          >
            <el-option
              v-for="item in classOptions"
              :key="item.classId"
              :label="item.name"
              :value="item.classId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="协议类型" prop="deviceProtocolId">
          <el-select
            v-model="form.deviceProtocolId"
            placeholder="请选择协议类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in protocolOptions"
              :key="item.protocolId"
              :label="item.name"
              :value="item.protocolId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="建筑物" prop="deviceBuildingId">
          <el-select
            v-model="form.deviceBuildingId"
            placeholder="请选择建筑物"
            style="width: 100%"
          >
            <el-option
              v-for="item in buildingOptions"
              :key="item.buildingId"
              :label="item.name"
              :value="item.buildingId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型" prop="type">
          <el-select
            v-model="form.type"
            placeholder="请选择设备类型"
            style="width: 100%"
            @change="handleDeviceTypeChange"
          >
            <el-option
              v-for="item in deviceTypeOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="设备行为" prop="action">
          <el-select
            v-model="form.action"
            placeholder="请选择设备行为"
            style="width: 100%"
            multiple
            filterable
            allow-create
          >
            <el-option
              v-for="item in filteredActionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="扩展信息" prop="Extension">
          <el-input
            v-model="form.Extension"
            type="textarea"
            placeholder="请输入扩展信息"
          />
        </el-form-item> -->
        <el-form-item label="控制模式" prop="controlType">
          <el-radio-group v-model="form.controlType">
            <el-radio :label="0">手动</el-radio>
            <el-radio :label="1">自动</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Device">
import {
  listDevice,
  //   getDevice,
  addDevice,
  //   updateDevice,
  delDevice,
} from "@/api/asset/device";
import { listGroup } from "@/api/asset/group";
// import { listClass } from "@/api/asset/class";
// import { listProtocol } from "@/api/asset/protocol";
// import { listBuilding } from "@/api/asset/building";

const { proxy } = getCurrentInstance();

const deviceList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const submitLoading = ref(false);

// 下拉选项数据
const groupOptions = ref([]);
const classOptions = ref([]);
const protocolOptions = ref([]);
const buildingOptions = ref([]);
const filteredActionOptions = ref([]);

// 设备分类模拟数据
const mockClassOptions = [
  { classId: "0", name: "照明设备" },
  { classId: "1", name: "空调设备" },
  { classId: "3", name: "水电设备" },
  { classId: "4", name: "安防设备" },
  { classId: "5", name: "门禁设备" },
  { classId: "6", name: "监控设备" },
  { classId: "7", name: "电梯设备" },
  { classId: "8", name: "消防设备" },
];

// 协议类型模拟数据
const mockProtocolOptions = [
  { protocolId: "0", name: "MQTT" },
  { protocolId: "2", name: "HTTP" },
  { protocolId: "3", name: "TCP/IP" },
  { protocolId: "4", name: "Modbus" },
  { protocolId: "5", name: "BACnet" },
  { protocolId: "6", name: "KNX" },
  { protocolId: "7", name: "Zigbee" },
];

// 建筑物模拟数据
const mockBuildingOptions = [
  { buildingId: "0", name: "A栋办公楼" },
  { buildingId: "2", name: "B栋宿舍楼" },
  { buildingId: "3", name: "C栋生产车间" },
  { buildingId: "4", name: "D栋研发中心" },
  { buildingId: "5", name: "E栋数据中心" },
  { buildingId: "6", name: "F栋实验室" },
];

// 设备类型模拟数据
const deviceTypeOptions = [
  "LED灯",
  "中央空调",
  "分体空调",
  "新风系统",
  "摄像头",
  "门禁卡读卡器",
  "电子锁",
  "电表",
  "水表",
  "温湿度传感器",
  "烟雾报警器",
  "智能窗帘",
];

// 设备行为模拟数据（根据设备类型提供不同的行为选项）
const deviceActionOptions = {
  LED灯: [
    { label: "开关", value: "switch" },
    { label: "亮度调节", value: "brightness" },
    { label: "色温调节", value: "color_temp" },
    { label: "RGB调色", value: "rgb_color" },
  ],
  中央空调: [
    { label: "开关", value: "switch" },
    { label: "制冷", value: "cooling" },
    { label: "制热", value: "heating" },
    { label: "除湿", value: "dehumidify" },
    { label: "送风", value: "fan" },
    { label: "温度调节", value: "temperature" },
    { label: "风速调节", value: "fan_speed" },
  ],
  分体空调: [
    { label: "开关", value: "switch" },
    { label: "制冷", value: "cooling" },
    { label: "制热", value: "heating" },
    { label: "除湿", value: "dehumidify" },
    { label: "送风", value: "fan" },
    { label: "温度调节", value: "temperature" },
    { label: "风速调节", value: "fan_speed" },
    { label: "扫风", value: "swing" },
  ],
  新风系统: [
    { label: "开关", value: "switch" },
    { label: "风速调节", value: "fan_speed" },
    { label: "换气模式", value: "ventilation_mode" },
  ],
  摄像头: [
    { label: "开关", value: "switch" },
    { label: "录像", value: "record" },
    { label: "拍照", value: "capture" },
    { label: "云台控制", value: "ptz" },
    { label: "变焦", value: "zoom" },
  ],
  门禁卡读卡器: [
    { label: "读卡", value: "read_card" },
    { label: "门禁开关", value: "door_control" },
    { label: "授权管理", value: "auth_manage" },
  ],
  电子锁: [
    { label: "开锁", value: "unlock" },
    { label: "关锁", value: "lock" },
    { label: "临时密码", value: "temp_password" },
  ],
  电表: [
    { label: "电量读取", value: "read_electricity" },
    { label: "峰谷电量", value: "peak_valley_electricity" },
    { label: "功率监测", value: "power_monitoring" },
  ],
  水表: [
    { label: "水量读取", value: "read_water" },
    { label: "流量监测", value: "flow_monitoring" },
  ],
  温湿度传感器: [
    { label: "温度读取", value: "read_temperature" },
    { label: "湿度读取", value: "read_humidity" },
    { label: "阈值报警", value: "threshold_alarm" },
  ],
  烟雾报警器: [
    { label: "烟雾检测", value: "smoke_detection" },
    { label: "报警触发", value: "alarm_trigger" },
    { label: "自检", value: "self_check" },
  ],
  智能窗帘: [
    { label: "开启", value: "open" },
    { label: "关闭", value: "close" },
    { label: "暂停", value: "pause" },
    { label: "位置调节", value: "position" },
  ],
};
const formateClass = (id) => {
  const text = "";
  const arr = mockClassOptions.filter((item) => item.classId == id);
  console.log(arr, "44");
  return arr[0].name;
};
const formateProtocol = (id) => {
  const text = "";
  const arr = mockProtocolOptions.filter((item) => item.protocolId == id);
  console.log(arr, "44");
  return arr[0].name;
};
const formateBuilding = (id) => {
  const text = "";
  const arr = mockBuildingOptions.filter((item) => item.buildingId == id);
  console.log(arr, "44");
  return arr[0].name;
};
// 处理设备类型变化，更新设备行为选项
function handleDeviceTypeChange(value) {
  if (value && deviceActionOptions[value]) {
    filteredActionOptions.value = deviceActionOptions[value];
  } else {
    filteredActionOptions.value = [];
    console.log("设备类型变更，未找到对应行为选项:", value);
  }
  // 如果切换设备类型，清空已选的行为
  form.value.action = [];
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    number: undefined,
    deviceGroupId: undefined,
    deviceClassId: undefined,
  },
  rules: {
    name: [{ required: true, message: "设备名称不能为空", trigger: "blur" }],
    number: [{ required: true, message: "设备编号不能为空", trigger: "blur" }],
    deviceGroupId: [
      { required: true, message: "请选择设备分组", trigger: "change" },
    ],
    deviceClassId: [
      { required: true, message: "请选择设备分类", trigger: "change" },
    ],
    deviceProtocolId: [
      { required: true, message: "请选择协议类型", trigger: "change" },
    ],
    deviceBuildingId: [
      { required: true, message: "请选择建筑物", trigger: "change" },
    ],
    type: [{ required: true, message: "请选择设备类型", trigger: "change" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询设备列表 */
function getList() {
  loading.value = true;
  listDevice(queryParams.value).then((response) => {
    deviceList.value = response.data.rows;
    total.value = response.data.total;
    loading.value = false;
  });
}

// 获取所有下拉选项数据
function getOptionData() {
  // 获取分组数据
  listGroup().then((response) => {
    groupOptions.value = response.data.rows || [];
  });

  // 模拟获取分类数据
  new Promise((resolve) => {
    setTimeout(() => {
      classOptions.value = mockClassOptions;
      resolve();
    }, 100);
  });

  // 模拟获取协议数据
  new Promise((resolve) => {
    setTimeout(() => {
      protocolOptions.value = mockProtocolOptions;
      resolve();
    }, 100);
  });

  // 模拟获取建筑物数据
  new Promise((resolve) => {
    setTimeout(() => {
      buildingOptions.value = mockBuildingOptions;
      resolve();
    }, 100);
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    deviceId: undefined,
    name: undefined,
    number: undefined,
    deviceGroupId: undefined,
    deviceClassId: undefined,
    deviceProtocolId: undefined,
    deviceBuildingId: undefined,
    type: undefined,
    action: undefined,
    extension: {},
    controlType: 0,
  };
  filteredActionOptions.value = [];
  proxy.resetForm("deviceRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {

  Object.keys(queryParams.value).forEach((key) => {
    queryParams.value[key] = undefined;
  });
  queryParams.value.pageSize = 10
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.deviceId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  form.value = Object.assign({}, form.value, row);

  // 根据设备类型加载对应的行为选项
  if (form.value.Type && deviceActionOptions[form.value.Type]) {
    filteredActionOptions.value = deviceActionOptions[form.value.Type];
  } else {
    // 如果没有匹配到行为选项，清空选项列表
    filteredActionOptions.value = [];
    console.log("未找到设备类型对应的行为选项:", form.value.Type);
  }

  open.value = true;
  title.value = "修改设备";
}

/** 设备详情 */
function handleDetail(row) {
  // 跳转到设备详情页或者显示详情弹窗
  proxy.$modal.msgInfo("查看设备详情: " + row.name);
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deviceRef"].validate((valid) => {
    if (valid) {
      submitLoading.value = true;
      if (form.value.deviceId != undefined) {
        addDevice(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).catch(() => {
          
        }).finally(() => {
          submitLoading.value = false;
        });
      } else {
        addDevice(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).catch(() => {
          
        }).finally(() => {
          submitLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const deviceIds = row.deviceId || ids.value;
  proxy.$modal
    .confirm('是否确认删除设备编号为"' + deviceIds + '"的数据项？')
    .then(function () {
      return delDevice(deviceIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

// 页面初始化
onMounted(() => {
  getList();
  getOptionData();
});
</script>
